import { useQuery } from "@tanstack/react-query";

import { useAuth } from "@/contexts/auth-context";
import { useApiFetch } from "@/lib/api-fetcher";
import type { ProjectSummary } from "@/lib/types";

export function useProjectsQuery(initialData?: ProjectSummary[]) {
  const fetcher = useApiFetch();
  const { tokens } = useAuth();

  return useQuery<ProjectSummary[], Error>({
    queryKey: ["projects"],
    queryFn: async () => {
      if (!tokens) {
        return [];
      }

      return fetcher<ProjectSummary[]>({ path: "/projects" });
    },
    initialData: initialData ?? [],
    enabled: Boolean(tokens),
    staleTime: 30 * 1000,
  });
}
